<?php

/*
 * Yanis Framework, Yet ANother Internet Service for web and mobile technologists
 * @copyright Copyright (C) 2011 ch@rlesen. All rights reserved.
 * @license GNU/GPL
 * @author Charles EDOU NZE <charles at charlesen.fr>
 */

/**
 * Database Management
 * 
 * Classe Mysqldb
 *
 */
class Mysqldb {

    /**
     * Multiple database connections are possible
     * Each session is stored in a special variable, active one is maintained
     */
    private $connections = array();

    /**
     * Tells de Database object which connection to use
     * setActiveConnection($id) allows us to change this
     */
    private $activeConnection = 0;

    /**
     * Queries which have been executed and the results cached for later
     * Template Engin ? Maybe
     */
    private $queryCache = array();

    /**
     * Data which has been prepared and then cached for later usage
     * Template Engine ? Maybe
     */
    private $dataCache = array();

    /**
     * Number of queries during execution process
     */
    private $queryCounter = 0;

    /**
     * Record of the last query
     */
    private $lastQuery;

    /**
     * @var Object The Registry object 
     */
    private $registry;

    /**
     * Construct the Database object
     * @param Registry $registry 
     */
    public function __construct(Registry $registry) {
        $this->registry = $registry;
    }

    /**
     * Create a new database connection
     * @param String database hostname
     * @param String database username
     * @param String password
     * @param String database the current database
     * @return int the id of the new connection
     */
    public function yConnect() {
        /**
         * Create a new instance of the Config Class and start connection
         */
        require_once '../../../config.php';
        $yconfig = new YConfig();
        $this->connections[] = new mysqli($yconfig->host, $yconfig->user, $yconfig->password, $yconfig->db);
        $connection_id = count($this->connections) - 1;
        if (mysql_connect_errno()) {
            trigger_error('Oups! Error connecting to host. ' . $this->connections[$connection_id]->error, E_USER_ERROR);
        }

        return $connection_id;
    }

    /**
     *
     * @param int the new connection id
     */
    public function setActiveConnection(int $new) {
        $this->activeConnection = $new;
    }

    /**
     * Execute a query string
     * @param String the query
     * @return void
     */
    public function yQuery($query) {
        if (!$result = $this->connections[$this->activeConnection]->query($query)) {
            trigger_error('Error executing query : ' . $query . ' - ' . $this->connections[$this->activeConnection]->error, E_USER_ERROR);
        } else {
            $this->lastQuery = $result;
        }
    }

    /**
     * Get rows from a query
     * @return array
     */
    public function getRows() {
        return $this->lastQuery->fetch_array(MYSQLI_ASSOC);
    }

    /**
     * Number of rows
     */
    public function numRows() {
        return $this->lastQuery->num_rows;
    }

    /**
     * Gets the number of affected rows from the previous query
     * @return int the number of affected rows
     */
    public function affectedRows() {
        return $this->lastQuery->affected_rows;
    }

    /**
     * Delete records from the database
     * @param String the table to remove rows from
     * @param String the condition for which rows are to be removed
     * @param int the number of rows to be removed
     * @return void
     */
    public function yDelete($table, $condition, $limit) {
        $limit = ( $limit == '') ? '' : 'LIMIT ' . $limit;
        $delete = "DELETE FROM {$table} WHERE {$condition} {$limit}";
        $this->yQuery($delete);
    }

    /**
     * Update records in the database
     * @param String the table
     * @param array of changes
     * @param String the condition
     * @return bool
     */
    public function yUpdate($table, $changes, $condition) {
        $update = "UPDATE " . $table . " SET";
        foreach ($changes as $field => $value) {
            $update .= "`" . $field . "`='{$value}',";
        }
        //Remove the last char
        $update = substr($update, 0, -1);
        if ($condition != '') {
            $update .="WHERE " . $condition;
        }
        $this->yQuery($update);

        return true;
    }

    /**
     * Insert records into the database
     * @param String the database table
     * @param array data to insert
     * @return bool
     */
    public function yInsert($table, $data) {
        $fields = "";
        $values = "";

        foreach ($data as $key => $value) {
            $fields .="`$key`";
            $values .=(is_numeric($value) && (intval($value) == $value)) ? $value . "," : "'$value'";
        }
        //Remove the last char
        $fields = substr($fields, 0, -1);
        $values = substr($values, 0, -1);

        $insert = "INSERT INTO $table ({$fields}) VALUES ({$values})";
        $this->yQuery($insert);

        return true;
    }

    /**
     * Sanitize data
     * @param String the data to be sanitized
     * @return String the sanitized data
     */
    public function sanitizedData($value) {
        //Stripslashes
        if (get_magic_quotes_gpc()) {
            $value = stripslashes($value);
        }

        //Quote value
        if (version_compare(phpversion(), "4.3.0") == "-1") {
            $value = $this->connections[$this->activeConnection]->escape_string($value);
        } else {
            $value = $this->connections[$this->activeConnection]->real_escape_string($value);
        }

        return value;
    }

    /**
     * Distroy the object
     * Close all of the database connections
     */
    public function __destruct() {
        foreach ($this->connections as $connection) {
            $connection->close();
        }
    }

}

?>